
<template>
    <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item>短信查询</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容区域 -->
    <el-card>
        <el-form :model="queryInfo" ref="queryForm" :rules="queryFormRules" size="small" :inline="true" label-width="90px">
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="queryInfo.phoneNumber" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item label="搜索日期" prop="sendDate">
            <el-date-picker
                v-model="queryInfo.sendDate"
                align="right"
                type="date"
                placeholder="选择日期"
                value-format="yyyyMMdd"
                :picker-options="pickerOptions">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary" icon="el-icon-search" size="mini">搜索</el-button>
          <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增按钮 -->
      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTaskHandle">发送短信</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="userList" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="outId" label="流水号"  align="center"> </el-table-column>
        <el-table-column prop="errCode" label="运营商短信状态码"  align="center"> 
          <!-- DELIVERED 发送成功 否则失败 -->
          <template slot-scope="scope">
                <span v-if="scope.row.errCode === 'DELIVERED'">发送成功</span>
                <span v-else >发送失败</span>
            </template>
        </el-table-column>
        <el-table-column prop="templateCode" label="短信模板代码"  align="center"> </el-table-column>
        <el-table-column prop="receiveDate" label="短信接收日期"  align="center" width="160px"> </el-table-column>
        <el-table-column prop="sendDate" label="短信发送日期"  align="center" width="160px"> </el-table-column>
        <el-table-column prop="phoneNum" label="接收短信的手机号"  align="center"> </el-table-column>
        <el-table-column prop="content" label="短信内容"  align="center">
            <template slot-scope="scope">
                <el-popover placement="top-start" width="300" trigger="hover">
                    <p>{{scope.row.content}}</p>
                    <div slot="reference" class="name-wrapper">
                        <el-button type="text" size="medium">{{scope.row.content}}</el-button>
                    </div>
                </el-popover>
            </template>
        </el-table-column>  
        <el-table-column prop="sendStatus" label="短信发送状态"  align="center">
            <!-- 1：等待回执。2：发送失败。3：发送成功。 -->
            <template slot-scope="scope">
                <span v-if="scope.row.sendStatus === '1'">等待回执</span>
                <span v-if="scope.row.sendStatus === '2'">发送失败</span>
                <span v-if="scope.row.sendStatus === '3' ">发送成功</span>
            </template>
        </el-table-column>  
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 弹出框 发送短信-->
    <el-dialog :title="upload.title" width="600px"  :visible.sync="dialogVisible" @close="addDialogClosed" append-to-body> 
      <!-- 内容主题区域 -->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="手机号" prop="phoneNumbers">
                <el-input v-model="addForm.phoneNumbers" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="短信签名" prop="signName">
              <el-select v-model="addForm.signName" placeholder="请选择短信签名"
              clearable
              style="width: 100%;">
                <el-option
                  v-for="item in signOptions "
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="短信模板" prop="templateCode">
              <el-select v-model="addForm.templateCode" placeholder="请选择短信模板"
              ref="mySelect"
              clearable
              style="width: 100%;"
              @change="handleSelectChange">
                <el-option
                  v-for="item in modelOptions "
                  :key="item.value"
                  :label="item.label"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" v-if="modelContent.length>0">
            <el-form-item label="短信参数" prop="map">
              <div v-for="(item,index) in modelContent" :key="index" style="display: flex;">
                <span style="width: 160px;margin-bottom: 10px;">{{item}}:</span>
                <el-input v-model="addForm.map[item]" placeholder="请输入短信参数"></el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleOk">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'querySms',
  data () {
    return {
        userList: [],
        total:0,
        queryInfo: {
            phoneNumber: '',
            sendDate: '',
            // 当前的页数
            currentPage: 1,
            // 当前每页显示多少条数据
            pageSize: 10,
      },
      queryFormRules:{
        phoneNumber: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
          ],
          sendDate:[
            { required: true, message: '请选择时间', trigger: 'blur' },
          ]
      } ,
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        addForm: {
            phoneNumbers: '',
            signName: '',
            templateCode: '',
            map: {}
        },
        addFormRules: {
            phoneNumbers: [
                { required: true, message: '请输入手机号码', trigger: 'blur' },
                { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
            ],
            signName: [
                { required: true, message: '请输入签名名称', trigger: 'blur' },
            ],
            templateCode: [
                { required: true, message: '请输入短信模板', trigger: 'blur' },
            ],
        },
        // 用户导入参数
        upload: {
            // 弹出层标题（用户导入）
            title: '',
          }, 
        dialogVisible: false,
        modelOptions: [],//模板下拉框选项
        signOptions: [],//签名下拉框选项
        modelContent:[],//对其便利的数组
    }
  },
  methods: {
    // 搜索按钮操作
    handleQuery() {
      this.queryInfo.currentPage = 1
      this.$refs['queryForm'].validate(async valid => {
        if (!valid) return
        this.querySms()
      })
    },
    // 重置按钮操作
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.querySms()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.currentPage = newPage
      this.querySms()
    },
    async querySms () {
        const params = this.queryInfo
        const { data: res } = await this.$http.post('/note/sendQuery', params)
        if (res.code === 20000) {
          this.userList = res.data.body.smsSendDetailDTOs.smsSendDetailDTO
          this.total = parseInt(res.data.body.totalCount)
        } else {
          this.$message.error(res.msg)
        }
    },
    async queryModel () {
      const { data: res } = await this.$http.post('/note/modelPage',{
          isPage:false
        })
        if (res.code === 20000) {
          let arr =res.data.body.smsTemplateList
          this.modelOptions = arr.map(item => {
            return {
              label: item.templateName,
              value: item.templateCode,
              templateContent:item.templateContent
            }
          })
        } else {
          this.$message.error(res.msg)
        }
    },
    async querySign () {
      const { data: res } = await this.$http.post('/note/signPage',{
          isPage:false
        })
        if (res.code === 20000) {
          let arr =res.data.body.smsSignList
          this.signOptions = arr.map(item => {
            return {
              label: item.signName,
              value: item.signName
            }
          })
        } else {
          this.$message.error(res.msg)
        }
    },
    async addTaskHandle () {
        this.dialogVisible = true
        this.upload.title = '发送短信'
    },
    addDialogClosed () {
        this.$refs['addFormRef'].resetFields()
        this.modelContent=[]
    },
    handleOk () {
        this.$refs['addFormRef'].validate(async valid => {
            if (!valid) return
            const params = {
                ...this.addForm,
                templateCode: this.addForm.templateCode.value,
                //如果map这个对象不为空，就JSON.parse(this.addForm.map) 为空就是空对象
                map: Object.keys(this.addForm.map).length !== 0 ? this.addForm.map : {}
            }
            console.log(params);
            const { data: res } = await this.$http.post('/note/sendSms', params)
            if (res.code === 20000) {
                this.$message.success('发送成功')
                this.dialogVisible = false
            } else {
                this.$message.error(res.msg)
            }
        })
    },
    handleSelectChange (item) {
      function extractVariables(message) {
        const regex = /\${(.*?)}/g;
        const matches = [];
        let match;
        while ((match = regex.exec(message)) !== null) {
          matches.push(match[1]);
        }
        return matches;
      }
      let content = item.templateContent
      // let content = '尊敬的${username},您发布的${ivtName}将在${time}进行开标,请登录http://item.qizhkj.com:11301查看详情。'
      this.modelContent = extractVariables(content)
    }
  },
  created() {
    this.queryModel()
    this.querySign()
  },
}
</script>
